//
//  NSObject+LLArchiver.m
//  TaoTuo
//
//  Created by admin on 2019/8/30.
//  Copyright © 2019 admin. All rights reserved.
//

#import "NSObject+LLArchiver.h"
#import <objc/runtime.h>

@implementation NSObject (LLArchiver)

- (void)encode:(NSCoder *)aCoder
{
    Class clazz = self.class;
    // 如果类存在，并且这个类不是NSObject，就继续进行编码
    while (clazz && clazz != [NSObject class]) {
        
        // 取出所有属性和实例变量
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList(clazz, &count);
        for (int i = 0; i < count; i++) {
            
            const char *name = ivar_getName(ivars[i]);
            NSString *key = [[NSString alloc] initWithUTF8String:name];
//            NSLog(@"> key = %@", key);
            
            // 使用 KVC 方式取值
            id value = [self valueForKey:key];
            
            [aCoder encodeObject:value forKey:key];
            
        }
        free(ivars);
        clazz = [clazz superclass];
    }
    
    
}


- (void)decode:(NSCoder *)aDecoder
{
    Class clazz = self.class;
    // 如果类存在，并且这个类不是NSObject，就继续进行解码
    while (clazz && clazz != [NSObject class]) {
        
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList(clazz, &count);
        for (int i = 0; i < count; i++) {
            
            const char *name = ivar_getName(ivars[i]);
            NSString *key = [[NSString alloc] initWithUTF8String:name];
            
            id value = [aDecoder decodeObjectForKey:key];
            
            if (value && key) {
                // 使用 KVC 方式赋值
                [self setValue:value forKey:key];
            }
        }
        free(ivars);
        clazz = [clazz superclass];
        
    }
    
    
}



@end
